import { AnyAction, Reducer } from 'redux';
import { EffectsCommandMap } from 'dva';
import { message } from 'antd';
import { fetchValidation } from '@/utils';
import {
  queryStatementsList,
  queryPartnersList,
  operUpdateMoney,
  operConfirm,
} from './service';

import { TableListData } from './data';

export interface StateType {
  datalist: TableListData;
  partnersList: any;
}

export type Effect = (
  action: AnyAction,
  effects: EffectsCommandMap & {
    select: <T>(func: (state: StateType) => T) => T;
  }
) => void;

export interface ModelType {
  namespace: string;
  state: StateType;
  effects: {
    fetch: Effect;
    getPartners: Effect;
    updateMoney: Effect;
    confirm: Effect;
  };
  reducers: {
    save: Reducer;
    partners: Reducer;
  };
}

const Model: ModelType = {
  namespace: 'statementsList',

  state: {
    datalist: {
      list: [],
      count: 0,
      user_type: '',
    },
    partnersList: [],
  },

  effects: {
    * fetch({ payload }, { call, put }) {
      const response = yield call(queryStatementsList, payload);
      const data = fetchValidation(response);
      yield data && put({
        type: 'save',
        payload: response.body,
      });
    },

    * getPartners({ payload = {} }, { call, put }) {
      payload.is_franchisee = 1;
      const response = yield call(queryPartnersList, payload);
      const data = fetchValidation(response);
      yield data && put({
        type: 'partners',
        payload: response.body ? data.body.list : [],
      });
    },

    * updateMoney({ payload: { search, ...query } }, { call, put }) {
      const response = yield call(operUpdateMoney, query);
      const data = fetchValidation(response);
      if (data) {
        message.success('修改成功');
        yield put({
          type: 'fetch',
          payload: search,
        });
      }
    },

    * confirm({ payload: { search, ...query } }, { call, put }) {
      const response = yield call(operConfirm, query);
      const data = fetchValidation(response);
      if (data) {
        message.success('修改成功');
        yield put({
          type: 'fetch',
          payload: search,
        });
      }
    },
  },

  reducers: {
    save(state, action) {
      return {
        ...state,
        datalist: action.payload,
      };
    },

    partners(state, action) {
      return {
        ...state,
        partnersList: action.payload,
      };
    },
  },
};

export default Model;
